package com.xy.webadmin.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xy.webadmin.app.service.*;
import com.xy.webadmin.app.dao.*;
import com.xy.webadmin.app.model.*;
import com.xy.webadmin.upms.service.SysUserService;
import com.xy.webadmin.upms.service.SysDeptService;
import com.xy.common.core.base.dao.BaseDaoMapper;
import com.xy.common.core.constant.GlobalDeletedFlag;
import com.xy.common.core.object.Tuple2;
import com.xy.common.core.object.TokenData;
import com.xy.common.core.object.MyRelationParam;
import com.xy.common.core.object.CallResult;
import com.xy.common.core.base.service.BaseService;
import com.xy.common.sequence.wrapper.IdGeneratorWrapper;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 教师数据操作服务类。
 *
 * @author xiaoyue
 * @date 2025-05-13
 */
@Slf4j
@Service("teacherService")
public class TeacherServiceImpl extends BaseService<Teacher, Long> implements TeacherService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private TeacherClazzMapper teacherClazzMapper;
    @Autowired
    private TeacherClazzService teacherClazzService;
    @Autowired
    private ClazzService clazzService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<Teacher> mapper() {
        return teacherMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Teacher saveNew(Teacher teacher) {
        teacherMapper.insert(this.buildDefaultValue(teacher));
        return teacher;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<Teacher> teacherList) {
        if (CollUtil.isNotEmpty(teacherList)) {
            teacherList.forEach(this::buildDefaultValue);
            teacherMapper.insertList(teacherList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewOrUpdateBatch(List<Teacher> teacherList, List<String> duplicateVerifyColumns, int batchSize) {
        if (CollUtil.isEmpty(teacherList)) {
            return;
        }
        if (batchSize <= 0) {
            batchSize = CollUtil.isNotEmpty(duplicateVerifyColumns) ? 100 : 10000;
        }
        int start = 0;
        do {
            int end = Math.min(teacherList.size(), start + batchSize);
            List<Teacher> subList = teacherList.subList(start, end);
            if (CollUtil.isNotEmpty(duplicateVerifyColumns)) {
                Tuple2<List<Teacher>, List<Teacher>> t = this.deduceInsertOrUpdateList(subList, duplicateVerifyColumns);
                if (CollUtil.isNotEmpty(t.getFirst())) {
                    t.getFirst().forEach(this::buildDefaultValue);
                    teacherMapper.insertList(t.getFirst());
                }
                t.getSecond().forEach(data -> teacherMapper.updateById(data));
            } else {
                teacherList.forEach(this::buildDefaultValue);
                teacherMapper.insertList(subList);
            }
            if (end == teacherList.size()) {
                break;
            }
            start += batchSize;
        } while (true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(Teacher teacher, Teacher originalTeacher) {
        teacher.setCreateUserId(originalTeacher.getCreateUserId());
        teacher.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        teacher.setCreateTime(originalTeacher.getCreateTime());
        teacher.setUpdateTime(new Date());
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<Teacher> uw = this.createUpdateQueryForNullValue(teacher, teacher.getId());
        return teacherMapper.update(teacher, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        if (teacherMapper.deleteById(id) == 0) {
            return false;
        }
        // 开始删除多对多子表的关联
        TeacherClazz teacherClazz = new TeacherClazz();
        teacherClazz.setTeacherId(id);
        teacherClazzMapper.delete(new QueryWrapper<>(teacherClazz));
        // 开始删除多对多父表的关联
        return true;
    }

    @Override
    public List<Teacher> getTeacherList(Teacher filter, String orderBy) {
        return teacherMapper.getTeacherList(filter, orderBy);
    }

    @Override
    public List<Teacher> getTeacherListWithRelation(Teacher filter, String orderBy) {
        List<Teacher> resultList = teacherMapper.getTeacherList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public List<Teacher> getNotInTeacherListByClazzId(Long clazzId, Teacher filter, String orderBy) {
        List<Teacher> resultList;
        if (clazzId != null) {
            resultList = teacherMapper.getNotInTeacherListByClazzId(clazzId, filter, orderBy);
        } else {
            resultList = getTeacherList(filter, orderBy);
        }
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        return resultList;
    }

    @Override
    public List<Teacher> getTeacherListByClazzId(
            Long clazzId, Teacher filter, TeacherClazz teacherClazzFilter, String orderBy) {
        List<Teacher> resultList =
                teacherMapper.getTeacherListByClazzId(clazzId, filter, teacherClazzFilter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForTeacherClazzList(resultList);
        return resultList;
    }

    @Override
    public Map<Long, List<Teacher>> getTeacherListMapByClazzList(
            List<Clazz> clazzList, Teacher filter, String orderBy) {
        List<Long> clazzIds = clazzList.stream().map(Clazz::getId).collect(Collectors.toList());
        List<Teacher> resultList =
                teacherMapper.getTeacherListByClazzIds(clazzIds, filter, orderBy);
        this.buildRelationForDataList(resultList, MyRelationParam.dictOnly());
        this.buildRelationForTeacherClazzList(resultList);
        return resultList.stream().collect(Collectors.groupingBy(s -> s.getTeacherClazz().getClazzId()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addTeacherClazzList(List<TeacherClazz> teacherClazzList, Long teacherId) {
        TokenData tokenData = TokenData.takeFromRequest();
        for (TeacherClazz teacherClazz : teacherClazzList) {
            teacherClazz.setId(idGenerator.nextLongId());
            teacherClazz.setTeacherId(teacherId);
            teacherClazz.setCreateTime(new Date());
            teacherClazz.setUpdateTime(new Date());
            teacherClazz.setCreateUserId(tokenData.getUserId());
            teacherClazz.setUpdateUserId(tokenData.getUserId());
            teacherClazzMapper.insert(teacherClazz);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateTeacherClazz(TeacherClazz teacherClazz) {
        TeacherClazz filter = new TeacherClazz();
        filter.setTeacherId(teacherClazz.getTeacherId());
        filter.setClazzId(teacherClazz.getClazzId());
        TeacherClazz originalOne = teacherClazzMapper.selectOne(new QueryWrapper<>(filter));
        teacherClazz.setCreateTime(originalOne.getCreateTime());
        teacherClazz.setUpdateTime(new Date());
        teacherClazz.setCreateUserId(originalOne.getCreateUserId());
        teacherClazz.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        UpdateWrapper<TeacherClazz> uw =
                BaseService.createUpdateQueryForNullValue(teacherClazz, TeacherClazz.class);
        uw.setEntity(filter);
        return teacherClazzMapper.update(teacherClazz, uw) > 0;
    }

    @Override
    public TeacherClazz getTeacherClazz(Long teacherId, Long clazzId) {
        TeacherClazz filter = new TeacherClazz();
        filter.setTeacherId(teacherId);
        filter.setClazzId(clazzId);
        return teacherClazzMapper.selectOne(new QueryWrapper<>(filter));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeTeacherClazz(Long teacherId, Long clazzId) {
        TeacherClazz filter = new TeacherClazz();
        filter.setTeacherId(teacherId);
        filter.setClazzId(clazzId);
        return teacherClazzMapper.delete(new QueryWrapper<>(filter)) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeTeacherClazzList(Long teacherId, List<Long> clazzIdList) {
        LambdaQueryWrapper<TeacherClazz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeacherClazz::getTeacherId, teacherId);
        queryWrapper.in(TeacherClazz::getClazzId, clazzIdList);
        teacherClazzMapper.delete(queryWrapper);
    }

    @Override
    public CallResult verifyImportList(List<Teacher> dataList, Set<String> ignoreFieldSet) {
        CallResult callResult;
        if (!CollUtil.contains(ignoreFieldSet, "sysUserId")) {
            callResult = verifyImportForDatasourceDict(dataList, "sysUserIdDictMap", Teacher::getSysUserId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "companyId")) {
            callResult = verifyImportForDatasourceDict(dataList, "companyIdDictMap", Teacher::getCompanyId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        return CallResult.ok();
    }

    @Override
    public CallResult verifyRelatedData(Teacher teacher, Teacher originalTeacher) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(teacher, originalTeacher, Teacher::getSysUserId)
                && !sysUserService.existId(teacher.getSysUserId())) {
            return CallResult.error(String.format(errorMessageFormat, "系统用户"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(teacher, originalTeacher, Teacher::getCompanyId)
                && !sysDeptService.existId(teacher.getCompanyId())) {
            return CallResult.error(String.format(errorMessageFormat, "公司"));
        }
        return CallResult.ok();
    }

    private void buildRelationForTeacherClazzList(List<Teacher> resultList) {
        List<TeacherClazz> teacherClazzList =
                resultList.stream().map(Teacher::getTeacherClazz).collect(Collectors.toList());
        teacherClazzService.buildRelationForDataList(teacherClazzList, MyRelationParam.dictOnly());
    }

    private Teacher buildDefaultValue(Teacher teacher) {
        if (teacher.getId() == null) {
            teacher.setId(idGenerator.nextLongId());
        }
        TokenData tokenData = TokenData.takeFromRequest();
        teacher.setCreateUserId(tokenData.getUserId());
        teacher.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        teacher.setCreateTime(now);
        teacher.setUpdateTime(now);
        teacher.setIsDeleted(GlobalDeletedFlag.NORMAL);
        return teacher;
    }
}
